package com.lucene.blog.controller;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import com.lucene.blog.bean.Blog;
import com.lucene.blog.bean.Comment;
import com.lucene.blog.db.service.BlogService;
import com.lucene.blog.db.service.CommentService;
import com.lucene.blog.util.ResponseUtil;

import net.sf.json.JSONObject;

/**
 * 评论的Controller层
 * @author yachao
 *
 */
@Controller
@RequestMapping("/comment")
public class CommentController {

	@Resource
	private CommentService commentService;
	@Resource
	private BlogService blogService;
	
	/**
	 * 添加或修改评论 
	 * @param comment
	 * @param imageCode
	 * @param request
	 * @param response
	 * @param session
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/save")
	public String save(Comment comment, @RequestParam("imageCode") String imageCode, 
					   HttpServletRequest request,
					   HttpServletResponse response,
					   HttpSession session) throws Exception {
		
		String sRand = (String) session.getAttribute("sRand");
		JSONObject result = new JSONObject();
		int resultTotal = 0;
		if(!imageCode.equals(sRand)) {
			result.put("success", false);
			result.put("errorInfo", "验证码有误!");
		} else {
			String userIP = request.getRemoteAddr();
			comment.setUserIP(userIP);
			if(comment.getCommentId() == null) { // 没有id表示添加
				resultTotal = commentService.addComment(comment);
				Blog blog = blogService.findBlogById(comment.getBlog().getBlogId());
				blog.setReplyHit(blog.getReplyHit() + 1);
				blogService.updateBlog(blog);
			} else { // 有id表示修改
				
			}
		}
		
		if(resultTotal > 0) {
			result.put("success", true);
		}
		ResponseUtil.write(response, result);
		return null;
	}
}
